<template>
    <div class="user-manage">
        <div class="query-form">
            <el-form ref="form" :inline="true" :model="queryForm">
                <el-form-item label="审批状态" prop="applyState">
                    <el-select v-model="queryForm.applyState">
                        <el-option value="" label="全部"></el-option>
                        <el-option :value="1" label="待审批"></el-option>
                        <el-option :value="2" label="审批中"></el-option>
                        <el-option :value="3" label="审批拒绝"></el-option>
                        <el-option :value="4" label="审批通过"></el-option>
                        <el-option :value="5" label="作废"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getApplyList">查询</el-button>
                    <el-button @click="handleReset('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <div class="action">
                <el-button type="primary" @click="handleApply"><i class="el-icon-bell"></i> 申请休假</el-button>
            </div>
            <el-table :data="applyList" :header-cell-style="{borderColor: '#ddd', color: '#333', backgroundColor: '#eee'}" border stripe>
                <el-table-column v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label" :width="item.width" :formatter="item.formatter" align="center">
                </el-table-column>
                <el-table-column label="休假原因" align="center">
                    <template #default="scope">
                        <el-popover placement="bottom" :width="300" trigger="click" :content="scope.row.reasons">
                            <template #reference>
                                <span class="reason">
                                    <i class="el-icon-view"></i>
                                    查看</span>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="审批状态" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.applyState === 1">待审批</el-tag>
                        <el-tag v-else-if="scope.row.applyState === 2">审批中</el-tag>
                        <el-tag v-else-if="scope.row.applyState === 3" type="danger">审批拒绝</el-tag>
                        <el-tag v-else-if="scope.row.applyState === 4" type="success">审批通过</el-tag>
                        <el-tag v-else-if="scope.row.applyState === 5" type="danger">作废</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template #default="scope">
                        <el-button size="mini" @click="handleDetail(scope.row)" type="primary">查看</el-button>
                        <el-button type="danger" size="mini" @click="handleDelete(scope.row._id)" v-if="[1, 2].includes(scope.row.applyState)">作废</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" :page-sizes="[8,10,15,20]" background layout="total,sizes,prev,pager,next" :total="pager.total" :page-size="pager.pageSize" @current-change="handleCurrentChange" @size-change="handelSizeChange" />
        </div>

        <el-dialog title="申请休假" v-model="showModal" width="50%" :close-on-click-modal="false" center>
            <el-form ref="dialogForm" :model="leaveForm" label-width="120px" :rules="rules">
                <el-form-item label="休假类型" prop="applyType" required>
                    <el-select v-model="leaveForm.applyType">
                        <el-option label="事假" :value="1"></el-option>
                        <el-option label="调休" :value="2"></el-option>
                        <el-option label="年假" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="休假类型" required>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item prop="startTime" required>
                                <el-date-picker v-model="leaveForm.startTime" type="date" placeholder="选择开始日期" @change="(val) => handleDateChange('startTime', val)" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="1">-</el-col>
                        <el-col :span="8">
                            <el-form-item prop="endTime" required>
                                <el-date-picker v-model="leaveForm.endTime" type="date" placeholder="选择结束日期" @change="(val) => handleDateChange('endTime', val)" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="休假时长" required>
                    {{ leaveForm.leaveTime }}
                </el-form-item>
                <el-form-item label="休假原因" prop="reasons" required>
                    <el-input type="textarea" :row="3" placeholder="请输入休假原因" v-model="leaveForm.reasons" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose">取 消</el-button>
                    <el-button type="primary" @click="handleSubmit">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog title="申请休假详情" width="55%" v-model="showDetailModal" center v-if="showDetailModal" @close="closeDialog" custom-class='detailDialog'>

            <el-steps :active="detail.applyState > 2 ? 3 : detail.applyState" align-center>
                <!-- 5作废 4通过 3拒绝 -->
                <el-step title="待审批"></el-step>
                <el-step title="审批中"></el-step>
                <el-step v-if="detail.applyState === 1 || detail.applyState === 2" title="审批通过/审批拒绝"></el-step>
                <el-step v-else-if="detail.applyState === 3" title="审批拒绝" status="error"></el-step>
                <el-step v-else-if="detail.applyState === 4" title="审批通过" status="success"></el-step>
                <el-step v-else-if="detail.applyState === 5" title="作废" status="error"></el-step>
            </el-steps>

            <div class="desc">
                <water-mask ref="watermask" v-if="detail.applyState === 5">
                </water-mask>
                <div class="row">
                    <div class="orderNo">请假人</div>
                    <div class="oderrNo2">{{detail.applyUser.userName}}</div>
                </div>
                <div class="row">
                    <div class="orderNo">单号</div>
                    <div class="oderrNo2">{{detail.orderNo}}</div>
                    <div class="orderNo">休假类型</div>
                    <div class="oderrNo2">{{detail.applyTypeName}}</div>
                </div>
                <div class="row">
                    <div class="orderNo">休假时间</div>
                    <div class="oderrNo2">{{detail.time}}</div>
                    <div class="orderNo">休假时长</div>
                    <div class="oderrNo2">{{detail.leaveTime}}</div>
                </div>
                <div class="row">
                    <div class="orderNo">请假原因</div>
                    <div class="oderrNo3">{{detail.reasons}}</div>
                </div>
                <div class="row">
                    <div class="orderNo">一级审核人</div>
                    <div class="oderrNo2">{{detail.auditFlows[0].userName}}</div>
                    <div class="orderNo">二级审核人</div>
                    <div class="oderrNo2">{{detail.auditFlows[1].userName}}</div>
                </div>
                <div class="row" v-if="detail.auditLogs[0]">
                    <div class="orderNo">一级审核人状态</div>
                    <div class="oderrNo2">
                        <el-tag size="small" :type="detail.auditLogs[0].action === '审核通过' ? 'success' : 'danger'">{{detail.auditLogs[0].action}}</el-tag>
                    </div>
                    <div class="orderNo">审核时间</div>
                    <div class="oderrNo2">{{detail.auditLogs[0].actionTime}}</div>
                    <!-- <div class="orderNo">二级审核人</div>
                    <div class="oderrNo2">
                        <el-tag size="small">{{detail.auditLogs[1].action}}</el-tag>
                    </div> -->
                </div>
                <div class="row" v-if="!detail.auditLogs[0] && detail.applyState !== 5">
                    <div class="orderNo">一级审核人状态</div>
                    <div class="oderrNo2">
                        <el-tag size="small" :type="primary">待审批</el-tag>
                    </div>
                    <div class="orderNo">审核时间</div>
                    <div class="oderrNo2"></div>
                    <!-- <div class="orderNo">二级审核人</div>
                    <div class="oderrNo2">
                        <el-tag size="small">{{detail.auditLogs[1].action}}</el-tag>
                    </div> -->
                </div>
                <div class="row" v-if="detail.auditLogs[0]">
                    <div class="orderNo">审核理由</div>
                    <div class="oderrNo3">
                        {{detail.auditLogs[0].remark}}
                    </div>
                </div>

                <div class="row" v-if="detail.auditLogs[1]">
                    <div class="orderNo">二级审核人状态</div>
                    <div class="oderrNo2">
                        <el-tag size="small" :type="detail.auditLogs[1].action === '审核通过' ? 'success' : 'danger'">{{detail.auditLogs[1].action}}</el-tag>
                    </div>
                    <div class="orderNo">审核时间</div>
                    <div class="oderrNo2">{{detail.auditLogs[1].actionTime}}</div>
                    <!-- <div class="orderNo">二级审核人</div>
                    <div class="oderrNo2">
                        <el-tag size="small">{{detail.auditLogs[1].action}}</el-tag>
                    </div> -->
                </div>
                <div class="row" v-if="!detail.auditLogs[1] && detail.applyState !== 5">
                    <div class="orderNo">二级审核人状态</div>
                    <div class="oderrNo2">
                        <el-tag size="small" :type="primary" v-if="detail.auditLogs[0]">待审批</el-tag>
                        <el-tag size="small" :type="primary" v-else>待一级审核人核批</el-tag>
                    </div>
                    <div class="orderNo">审核时间</div>
                    <div class="oderrNo2"></div>
                    <!-- <div class="orderNo">二级审核人</div>
                    <div class="oderrNo2">
                        <el-tag size="small">{{detail.auditLogs[1].action}}</el-tag>
                    </div> -->
                </div>
                <div class="row" v-if="detail.auditLogs[1]">
                    <div class="orderNo">审核理由</div>
                    <div class="oderrNo3">
                        {{detail.auditLogs[1].remark}}
                    </div>
                </div>



            </div>





            <!-- <el-form label-width="120px" label-suffix=":">
                <el-form-item label="休假类型">
                    <div>{{ detail.applyTypeName }}</div>
                </el-form-item>
                <el-form-item label="休假时间">
                    <div>{{ detail.time }}</div>
                </el-form-item>
                <el-form-item label="休假时长">
                    <div>{{ detail.leaveTime }}</div>
                </el-form-item>
                <el-form-item label="休假原因">
                    <div>{{ detail.reasons }}</div>
                </el-form-item>
                <el-form-item label="审批状态">
                    <div>{{ detail.applyStateName }}</div>
                </el-form-item>
                <el-form-item label="审批人">
                    <div>{{ detail.curAuditUserName }}</div>
                </el-form-item>
            </el-form> -->
        </el-dialog>


    </div>
</template>
<script>
    import { ElMessage, ElMessageBox } from 'element-plus'
    import waterMask from './waterMark.vue'
    import { getCurrentInstance, onMounted, reactive, ref, toRaw } from "vue";
    import utils from "../utils/utils";
    export default {
        name: "user",
        components: {
            waterMask
        },
        setup() {
            //   获取Composition API 上下文对象
            const { ctx } = getCurrentInstance();
            const queryForm = reactive({
                applyState: '',
            });
            const pager = reactive({
                pageNum: 1,
                pageSize: 8,
                total: 0,
            });
            // 定义动态表格-格式
            const columns = reactive([{
                    label: "单号",
                    prop: "orderNo",
                },
                {
                    width: '250px',
                    label: "休假时间",
                    prop: "",
                    formatter(row) {
                        return (
                            utils.formateDate(new Date(row.startTime), "yyyy-MM-dd") +
                            "到" +
                            utils.formateDate(new Date(row.endTime), "yyyy-MM-dd")
                        );
                    },
                },
                {
                    label: "休假时长",
                    prop: "leaveTime",
                },
                {
                    label: "休假类型",
                    prop: "applyType",
                    formatter(row, column, value) {
                        return {
                            1: "事假",
                            2: "调休",
                            3: "年假",
                        } [value];
                    },
                },
                // {
                //     label: "休假原因",
                //     prop: "reasons",
                // },
                {
                    label: "申请时间",
                    prop: "createTime",
                    width: 180,
                    formatter: (row, column, value) => {
                        return utils.formateDate(new Date(value));
                    },
                },
                {
                    label: "审批人",
                    prop: "auditUsers",
                },
                {
                    label: "当前审批人",
                    prop: "curAuditUserName",
                },
            ]);
            // 申请列表
            const applyList = ref([]);
            // 创建休假弹框表单
            const leaveForm = reactive({
                applyType: 1,
                startTime: "",
                endTime: "",
                leaveTime: "0天",
                reasons: "",
            });
            //create:创建 delete:作废
            const action = ref("create");
            const showModal = ref(false);
            const showDetailModal = ref(false);
            let detail = ref({});
            // 表单规则
            const rules = {
                startTime: [{
                    type: "date",
                    required: true,
                    message: "请选择开始日期",
                    trigger: "blur",
                }, ],
                endTime: [{
                    type: "date",
                    required: true,
                    message: "请选择结束日期",
                    trigger: "blur",
                }, ],
                reasons: [{
                    required: true,
                    message: "请输入休假原因",
                    trigger: ["change", "blur"],
                }, ],
            };
            // 初始化接口调用
            onMounted(() => {
                getApplyList();
            });

            // 加载申请列表
            const getApplyList = async () => {
                let params = { ...queryForm, ...pager };
                let { list, page } = await ctx.$api.getApplyList(params);
                applyList.value = list;
                pager.total = page.total;
            };
            // 重置查询表单
            const handleReset = (form) => {
                ctx.$refs[form].resetFields();
                getApplyList();
            };

            // 分页事件处理
            const handleCurrentChange = (current) => {
                pager.pageNum = current;
                getApplyList();
            };
            const handelSizeChange = (current) => {
                pager.pageSize = current
                getApplyList();

            }

            // 点击申请休假-展示弹框
            const handleApply = () => {
                showModal.value = true;
                action.value = "create";
            };
            // 弹框关闭
            const handleClose = () => {
                showModal.value = false;
                handleReset("dialogForm");
            };
            // 获取休假时长
            const handleDateChange = (key, val) => {
                if (utils.formateDate(val).substr(0, 10) !== utils.formateDate(new Date()).substr(0, 10) && val - new Date() < 0) {
                    console.log(utils.formateDate(val).substr(0, 10));
                    console.log(utils.formateDate(new Date()).substr(0, 10));
                    console.log(val - new Date());
                    ctx.$message.error("不能选择今天以前的日期!");
                    leaveForm.leaveTime = "0天";
                    setTimeout(() => {
                        leaveForm[key] = "";
                    }, 0);
                    return
                }
                let { startTime, endTime } = leaveForm;
                if (!startTime || !endTime) return;
                if (startTime > endTime) {
                    ctx.$message.error("开始日期不能晚于结束日期");
                    leaveForm.leaveTime = "0天";
                    setTimeout(() => {
                        leaveForm[key] = "";
                    }, 0);
                } else {
                    leaveForm.leaveTime =
                        (endTime - startTime) / (24 * 60 * 60 * 1000) + 1 + "天";
                }
            };
            // 申请提交
            const handleSubmit = () => {
                ctx.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        try {
                            let params = { ...leaveForm, action: action.value };
                            let res = await ctx.$api.leaveOperate(params);
                            ctx.$message.success("创建成功");
                            handleClose();
                            getApplyList();
                        } catch (error) {}
                    }
                });
            };

            const handleDetail = (row) => {
                let data = { ...row };
                data.applyTypeName = {
                    1: "事假",
                    2: "调休",
                    3: "年假",
                } [data.applyType];
                data.time =
                    utils.formateDate(new Date(data.startTime), "yyyy-MM-dd") +
                    "到" +
                    utils.formateDate(new Date(data.endTime), "yyyy-MM-dd");
                // 1:待审批 2:审批中 3:审批拒绝 4:审批通过 5:作废
                data.applyStateName = {
                    1: "待审批",
                    2: "审批中",
                    3: "审批拒绝",
                    4: "审批通过",
                    5: "作废",
                } [data.applyState];
                if (data.auditLogs[0]) {
                    data.auditLogs[0].actionTime = utils.formateDate(new Date(data.auditLogs[0].createTime))
                }
                if (data.auditLogs[1]) {
                    data.auditLogs[1].actionTime = utils.formateDate(new Date(data.auditLogs[1].createTime))
                }
                detail.value = data;
                showDetailModal.value = true;
            };

            const handleDelete = async (_id) => {
                ElMessageBox.confirm(
                        '是否确定作废?',
                        '提醒', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    )
                    .then(async () => {
                        try {
                            let params = { _id, action: "delete" };
                            let res = await ctx.$api.leaveOperate(params);
                            ctx.$message.success("删除成功");
                            getApplyList();
                        } catch (error) {}
                    })
                    .catch(() => {})

            };

            const closeDialog = () => {
                if (detail.applyState === 5) {
                    toRaw(ctx.$refs.watermask).removeMaskDiv()
                }
            }

            return {
                queryForm,
                pager,
                columns,
                handleCurrentChange,
                handelSizeChange,
                handleReset,
                getApplyList,
                applyList,
                leaveForm,
                showModal,
                showDetailModal,
                handleApply,
                handleClose,
                handleSubmit,
                rules,
                handleDateChange,
                detail,
                handleDetail,
                handleDelete,
                closeDialog
            };
        },
    };
</script>

<style scoped>
    .pagination {
        display: flex;
    }

    .reason {
        color: #65aaf1;
        cursor: pointer;
    }

    .desc {
        /* position: relative; */
        margin-top: 20px;
        margin: 20px;
        border: 1px solid #eee
    }

    .detailDialog {
        position: relative;
    }

    .row {
        display: flex;
        border-bottom: 1px solid #ebeef5
    }



    .orderNo {
        width: 25%;
        padding: 10px 20px;
        background: #fafafa;
        border-right: 1px solid #ebeef5;
        display: flex;
        align-items: center;
    }

    .oderrNo2 {
        width: 25%;
        padding: 10px 10px;
        display: flex;
        align-items: center;
    }

    .oderrNo3 {
        width: 75%;
        padding: 10px 10px;

    }
</style>